import nedb from './nedb'

export default {
  /**
   * 获取配置
   * @param {Object} user 用户信息
   */
  async getConfig () {
    var defaultConfig = {
      id: 0,
      notifi_sound: true,
      newmsg_mp3: require('../assets/audio/2.mp3'),
      subscribe_mp3: require('../assets/audio/1.mp3'),
      unsubscribe_mp3: require('../assets/audio/3.mp3')
    }
    try {
      var result = await nedb.config.find({id: 0})
      if (result[0]) {
        return Promise.resolve(result[0])
      } else {
        return Promise.resolve(defaultConfig)
      }
    } catch (e) {
      return Promise.resolve(defaultConfig)
    }
  },
  /**
   * 保存配置
   * @param {Number} id 客服ID
   */
  async setConfig (config) {
    config.id = 0
    try {
      var result = await nedb.config.find({id: 0})
      if (result[0]) {
        var update = await nedb.config.update({id: 0}, config)
        return Promise.resolve({
          status: 1,
          data: update
        })
      } else {
        var insert = await nedb.config.insert(config)
        return Promise.resolve({
          status: 1,
          data: insert
        })
      }
    } catch (e) {
      return Promise.resolve({
        status: -1,
        data: '保存数据库出错，请重试'
      })
    }
  }
}
